package com.example.registration.controller;

import com.example.registration.entity.Registration;
import com.example.registration.entity.RegistrationLimit;
import com.example.registration.service.RegistrationLimitService;
import com.example.registration.service.RegistrationService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private RegistrationService registrationService;

    @Autowired
    private RegistrationLimitService registrationLimitService;

    @GetMapping("/login")
    public String showLoginPage() {
        return "admin/login";
    }

    @GetMapping("/dashboard")
    public String showDashboard(Model model) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        model.addAttribute("username", auth.getName());
        
        // 获取所有报名信息并添加到模型中
        List<Registration> registrations = registrationService.getAllRegistrations();
        model.addAttribute("registrations", registrations);
        
        // 获取所有报名限制信息并添加到模型中
        List<RegistrationLimit> limits = registrationLimitService.getAllLimits();
        model.addAttribute("limits", limits);
        
        // 状态映射，用于在页面上显示友好的状态名称
        Map<String, String> statusMap = new HashMap<>();
        statusMap.put("PENDING", "待确认");
        statusMap.put("CONFIRMED", "已确认");
        statusMap.put("COMPLETED", "已完成");
        statusMap.put("CANCELLED", "已取消");
        model.addAttribute("statusMap", statusMap);
        
        return "admin/dashboard";
    }

    // 获取所有报名信息
    @GetMapping("/api/registrations")
    @ResponseBody
    public List<Registration> getAllRegistrations() {
        return registrationService.getAllRegistrations();
    }

    // 获取单个报名信息
    @GetMapping("/api/registrations/{id}")
    @ResponseBody
    public Registration getRegistrationById(@PathVariable Long id) {
        return registrationService.getRegistrationById(id);
    }

    // 更新报名状态
    @PutMapping("/api/registrations/{id}/status")
    @ResponseBody
    public Map<String, Object> updateRegistrationStatus(@PathVariable Long id, @RequestBody Map<String, String> statusMap) {
        Map<String, Object> response = new HashMap<>();
        String status = statusMap.get("status");
        
        boolean updated = registrationService.updateRegistrationStatus(id, status);
        
        response.put("success", updated);
        response.put("message", updated ? "状态更新成功" : "状态更新失败");
        return response;
    }

    // 删除报名
    @DeleteMapping("/api/registrations/{id}")
    @ResponseBody
    public Map<String, Object> deleteRegistration(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        
        boolean deleted = registrationService.deleteRegistration(id);
        
        response.put("success", deleted);
        response.put("message", deleted ? "删除成功" : "删除失败");
        return response;
    }

    // 导出报名信息到Excel
    @GetMapping("/api/registrations/export")
    public ResponseEntity<byte[]> exportRegistrations() throws IOException {
        List<Registration> registrations = registrationService.getAllRegistrations();
        
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("报名信息");
            
            // 设置表头
            Row headerRow = sheet.createRow(0);
            String[] columnHeaders = {"ID", "学生姓名", "年级", "家长姓名", "联系方式", "报名时间", "状态"};
            
            CellStyle headerStyle = workbook.createCellStyle();
            headerStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
            headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerStyle.setFont(headerFont);
            
            for (int i = 0; i < columnHeaders.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(columnHeaders[i]);
                cell.setCellStyle(headerStyle);
                sheet.setColumnWidth(i, 4000);
            }

            
            for (int i = 0; i < registrations.size(); i++) {
                Registration reg = registrations.get(i);
                Row row = sheet.createRow(i + 1);
                
                row.createCell(0).setCellValue(reg.getId());
                row.createCell(1).setCellValue(reg.getStudentName());
                row.createCell(2).setCellValue(reg.getGrade());
                row.createCell(3).setCellValue(reg.getParentName());
                row.createCell(4).setCellValue(reg.getContactPhone());
                row.createCell(5).setCellValue(reg.getCreateTime());
                
                String status = "";
                switch (reg.getStatus()) {
                    case "PENDING":
                        status = "待确认";
                        break;
                    case "CONFIRMED":
                        status = "已确认";
                        break;
                    case "COMPLETED":
                        status = "已完成";
                        break;
                    case "CANCELLED":
                        status = "已取消";
                        break;
                    default:
                        status = reg.getStatus();
                }
                row.createCell(6).setCellValue(status);
            }
            
            // 将工作簿写入字节数组
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            
            // 设置响应头
            HttpHeaders responseHeaders = new HttpHeaders();
            responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            String fileName = "报名信息_" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + ".xlsx";
            responseHeaders.setContentDispositionFormData("attachment", new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
            
            return new ResponseEntity<>(outputStream.toByteArray(), responseHeaders, HttpStatus.OK);
        }
    }

    // 获取所有报名限制
    @GetMapping("/api/limits")
    @ResponseBody
    public List<RegistrationLimit> getAllLimits() {
        return registrationLimitService.getAllLimits();
    }

    // 添加报名限制
    @PostMapping("/api/limits")
    @ResponseBody
    public Map<String, Object> addLimit(@RequestBody RegistrationLimit limit) {
        Map<String, Object> response = new HashMap<>();
        
        boolean added = registrationLimitService.addLimit(limit);
        
        response.put("success", added);
        response.put("message", added ? "添加成功" : "添加失败");
        return response;
    }

    // 删除报名限制
    @DeleteMapping("/api/limits/{id}")
    @ResponseBody
    public Map<String, Object> deleteLimit(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        
        boolean deleted = registrationLimitService.deleteLimit(id);
        
        response.put("success", deleted);
        response.put("message", deleted ? "删除成功" : "删除失败");
        return response;
    }
} 